package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ytjj.qmyx.supplychain.common.model.response.PCAResponse;
import com.ytjj.qmyx.supplychain.common.model.response.address.*;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import jdk.nashorn.internal.scripts.JS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class ProvincesService {
    @Resource
    private ProvincesMapper provincesMapper;
    @Resource
    private CitiesMapper citiesMapper;
    @Resource
    private AreasMapper areasMapper;
    @Autowired
    private RedisService redisService;
    @Resource
    private AreasNewMapper areasNewMapper;
    @Resource
    private ShopInfoMapper shopInfoMapper;

    public List<PCAResponse> getProvince(Integer id) {
        Example example = new Example(YxProvinces.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != id) {
            criteria.andEqualTo("id", id);
        }
        List<YxProvinces> list = provincesMapper.selectByExample(example);
        List<PCAResponse> returnList = new ArrayList<>();
        list.stream().forEach(item -> {
            PCAResponse response = new PCAResponse();
            response.setId(item.getId());
            response.setName(item.getProvince());
            response.setPid(item.getProvinceid());
            returnList.add(response);
        });
        return returnList;
    }

    public List<PCAResponse> getCity(int pids) {
        List<PCAResponse> cities = new ArrayList<>();
        //String[] pid = pids.split(",");
        //根据省份id查询省份编号
        List<PCAResponse> province = getProvince(pids);
        if (CollectionUtils.isEmpty(province)) {
            return cities;
        }
        Example example = new Example(YxCities.class);
        example.createCriteria().andEqualTo("provinceid", province.get(0).getPid());
        List<YxCities> list = citiesMapper.selectByExample(example);
        list.stream().forEach(item -> {
            PCAResponse response = new PCAResponse();
            response.setId(item.getId());
            response.setName(item.getCity());
            response.setCid(item.getCityid());
            response.setPid(item.getProvinceid());
            cities.add(response);
        });
        return cities;
    }

    /**
     * 根据多个省份id查询不同省份对应的城市集
     * @param pids 省份id集
     * @return List<YxProvinces>
     */
    public List<YxProvinces> getCitysBypids(String pids) {
        List<YxProvinces> provincesList = new ArrayList<>();
        String[] pidArray = pids.split(",");
        List<String> pidList = Arrays.asList(pidArray);
        if (!CollectionUtils.isEmpty(pidList)) {
            Example example = new Example(YxProvinces.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", pidList);
            provincesList = provincesMapper.selectByExample(example);
            provincesList.forEach(pro -> {
                Integer proId = pro.getProvinceid();
                Example example2 = new Example(YxCities.class);
                example2.createCriteria().andEqualTo("provinceid", proId);
                List<YxCities> list = citiesMapper.selectByExample(example2);
                pro.setCitys(list);
            });
        }
        return provincesList;
    }

    public List<PCAResponse> getArea(Integer cid) {
        YxCities cities = citiesMapper.selectByPrimaryKey(cid);
        if (null == cities) {
            return new ArrayList<>();
        }
        Example example = new Example(YxAreas.class);
        example.createCriteria().andEqualTo("cityid", cities.getCityid());
        List<YxAreas> list = areasMapper.selectByExample(example);
        List<PCAResponse> returnList = new ArrayList<>();
        list.stream().forEach(item -> {
            PCAResponse response = new PCAResponse();
            response.setId(item.getId());
            response.setName(item.getArea());
            response.setAid(item.getAreaid());
            response.setCid(item.getCityid());
            returnList.add(response);
        });
        return returnList;
    }

    public List<String> getBalckUsers(){
        return shopInfoMapper.getBalckUsers();
    }

    public String getH5Address(){
        String h5Address = redisService.get("address:h5");
        if (h5Address!=null){
            return h5Address;
        }

        List<H5Response> responses = Lists.newArrayList();
        Example provincesExample = new Example(YxProvinces.class);
        Example.Criteria criteria = provincesExample.createCriteria();
//        criteria.andEqualTo("id", 1);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);
        for (YxProvinces provinces:list){
            //香港 澳门 台湾 钓鱼岛
            if (provinces.getProvinceid().toString().equals("710000") || provinces.getProvinceid().toString().equals("810000")
                    || provinces.getProvinceid().toString().equals("820000") || provinces.getProvinceid().toString().equals("900000")){
                continue;
            }

            H5Response h5Response = new H5Response();
            h5Response.setName(provinces.getProvince());

            //省份下的城市
            Example example = new Example(YxCities.class);
            example.createCriteria().andEqualTo("provinceid", provinces.getProvinceid()).andEqualTo("isDeleted",0);
            List<YxCities> citiesList = citiesMapper.selectByExample(example);

            List<H5SubCityEntity> h5SubCityEntityList = Lists.newArrayList();
            for (YxCities city:citiesList){
                H5SubCityEntity h5SubCityEntity = new H5SubCityEntity();
                h5SubCityEntity.setName(city.getCity());

                //城市下的区
                List<H5NameEntity> nameEntityList = Lists.newArrayList();
                Example areaExample = new Example(YxAreas.class);
                areaExample.createCriteria().andEqualTo("cityid", city.getCityid()).andEqualTo("isDeleted",0);
                List<YxAreas> areasList = areasMapper.selectByExample(areaExample);
                for (YxAreas areas:areasList){
                    H5NameEntity h5NameEntity = new H5NameEntity();
                    h5NameEntity.setName(areas.getArea());
                    nameEntityList.add(h5NameEntity);
                }
                h5SubCityEntity.setSub(nameEntityList);
                h5SubCityEntityList.add(h5SubCityEntity);
            }
            h5Response.setSub(h5SubCityEntityList);
            responses.add(h5Response);
        }
        String json = JSON.toJSONString(responses);
        redisService.set("address:h5", json);
        return json;
    }

    public String getIOSAddress(){
        String iosAddress = redisService.get("address:ios");
        if (iosAddress!=null){
            return iosAddress;
        }
        List<IOSProvinceEntity> iosProvinceEntityList = Lists.newArrayList();

        Example provincesExample = new Example(YxProvinces.class);
        Example.Criteria criteria = provincesExample.createCriteria();
        criteria.andNotEqualTo("provinceid",710000).andNotEqualTo("provinceid",810000)
                .andNotEqualTo("provinceid",820000).andNotEqualTo("provinceid",900000);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);

        for (YxProvinces provinces:list){
            IOSProvinceEntity iosProvinceEntity = new IOSProvinceEntity();
            iosProvinceEntity.setName(provinces.getProvince());
            iosProvinceEntity.setCode(provinces.getProvinceid().toString());
            //省份下的城市
            Example example = new Example(YxCities.class);
            example.createCriteria().andEqualTo("provinceid", provinces.getProvinceid());
            List<YxCities> citiesList = citiesMapper.selectByExample(example);

            List<IOSCityEntity> iosCityEntityList = Lists.newArrayList();
            for (YxCities city:citiesList){
                IOSCityEntity iosCityEntity = new IOSCityEntity();
                iosCityEntity.setCode(city.getCityid().toString());
                iosCityEntity.setName(city.getCity());

                //城市下的区
                List<IOSAreaEntity> iosAreaEntityList = Lists.newArrayList();
                Example areaExample = new Example(YxAreas.class);
                areaExample.createCriteria().andEqualTo("cityid", city.getCityid()).andEqualTo("isDeleted",0);
                List<YxAreas> areasList = areasMapper.selectByExample(areaExample);
                for (YxAreas areas:areasList){
                    if (areas!=null && areas.getAreaid()!=null){
                        IOSAreaEntity iosAreaEntity = new IOSAreaEntity();
                        iosAreaEntity.setCode(areas.getAreaid().toString());
                        iosAreaEntity.setName(areas.getArea());
                        iosAreaEntityList.add(iosAreaEntity);
                    }
                }
                iosCityEntity.setAreaList(iosAreaEntityList);
                iosCityEntityList.add(iosCityEntity);
            }
            iosProvinceEntity.setCityList(iosCityEntityList);
            iosProvinceEntityList.add(iosProvinceEntity);
        }
        String json = JSON.toJSONString(iosProvinceEntityList);
        redisService.set("address:ios", json);
        return json;
    }

    public String getAndroidAddress(){
        String address = redisService.get("address:android");
        if (address!=null){
            return address;
        }
       List<AndroidProvinceEntity> androidProvinceEntityList = Lists.newArrayList();

        Example provincesExample = new Example(YxProvinces.class);
//        Example.Criteria criteria = provincesExample.createCriteria();
//        criteria.andEqualTo("id", 1);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);

        for (YxProvinces provinces:list){
            AndroidProvinceEntity androidProvinceEntity = new AndroidProvinceEntity();
            androidProvinceEntity.setName(provinces.getProvince());

            //省份下的城市
            Example example = new Example(YxCities.class);
            example.createCriteria().andEqualTo("provinceid", provinces.getProvinceid());
            List<YxCities> citiesList = citiesMapper.selectByExample(example);

            List<AndroidCityEntity> androidCityEntityList = Lists.newArrayList();
            for (YxCities city:citiesList){
                AndroidCityEntity androidCityEntity = new AndroidCityEntity();
                androidCityEntity.setName(city.getCity());


                //城市下的区
                List<String> areaEntityList = Lists.newArrayList();
                Example areaExample = new Example(YxAreas.class);
                areaExample.createCriteria().andEqualTo("cityid", city.getCityid());
                List<YxAreas> areasList = areasMapper.selectByExample(areaExample);
                for (YxAreas areas:areasList){
                    areaEntityList.add(areas.getArea());
                }
                androidCityEntity.setArea(areaEntityList);
                androidCityEntityList.add(androidCityEntity);

            }
            androidProvinceEntity.setCity(androidCityEntityList);
            androidProvinceEntityList.add(androidProvinceEntity);
        }
        String json = JSON.toJSONString(androidProvinceEntityList);
        redisService.set("address:android", json);
        return json;
    }

    public List<AddressEntity> provinceAddress(){
        Example provincesExample = new Example(YxProvinces.class);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);

        List<AddressEntity> addressEntityList = Lists.newArrayList();
        for (YxProvinces provinces:list){
            AddressEntity addressEntity = new AddressEntity();
            addressEntity.setLabel(provinces.getProvince());
            addressEntity.setValue(provinces.getProvinceid().toString());
            addressEntityList.add(addressEntity);
        }
        return addressEntityList;
    }

    public List<List<AddressEntity>> cityAddress(){
        Example provincesExample = new Example(YxProvinces.class);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);

        List<List<AddressEntity>> provinceList = Lists.newArrayList();
        for (YxProvinces provinces:list){

            //省份下的城市
            Example example = new Example(YxCities.class);
            example.createCriteria().andEqualTo("provinceid", provinces.getProvinceid());
            List<YxCities> citiesList = citiesMapper.selectByExample(example);

            List<AddressEntity> cityList = Lists.newArrayList();
            for (YxCities city:citiesList){
                AddressEntity addressEntity = new AddressEntity();
                addressEntity.setLabel(city.getCity());
                addressEntity.setValue(city.getCityid().toString());
                cityList.add(addressEntity);
            }
            provinceList.add(cityList);
        }
        return provinceList;
    }

    public List<List<List<AddressEntity>>> areaAddress(){
        Example provincesExample = new Example(YxProvinces.class);
        List<YxProvinces> list = provincesMapper.selectByExample(provincesExample);

        List<List<List<AddressEntity>>> provinceList = Lists.newArrayList();
        for (YxProvinces provinces:list){
            //省份下的城市
            Example example = new Example(YxCities.class);
            example.createCriteria().andEqualTo("provinceid", provinces.getProvinceid());
            List<YxCities> citiesList = citiesMapper.selectByExample(example);

            List<List<AddressEntity>> cityList = Lists.newArrayList();
            for (YxCities city:citiesList){

                //城市下的区
                List<AddressEntity> areaEntityList = Lists.newArrayList();
                Example areaExample = new Example(YxAreas.class);
                areaExample.createCriteria().andEqualTo("cityid", city.getCityid());
                List<YxAreas> areasList = areasMapper.selectByExample(areaExample);
                for (YxAreas areas:areasList){
                    AddressEntity addressEntity = new AddressEntity();
                    addressEntity.setLabel(areas.getArea());
                    addressEntity.setValue(areas.getAreaid().toString());
                    areaEntityList.add(addressEntity);
                }
                cityList.add(areaEntityList);
            }
            provinceList.add(cityList);
        }
        return provinceList;
    }

    public String getAllAddress(){
        String address = redisService.get("address:all");
        if (address!=null){
            return address;
        }

        List<AddressEntity> province = this.provinceAddress();
        List<List<AddressEntity>> city = this.cityAddress();
        List<List<List<AddressEntity>>> area = this.areaAddress();

        Map<String, Object> map = new HashMap<>();
        map.put("provinceData",province);
        map.put("cityData",city);
        map.put("areaData",area);

        String json = JSON.toJSONString(map);
        redisService.set("address:all", json);
        return json;
    }

    public Map<String, String> addressChange(String province,String city,String area){
        String provinceResult = provincesMapper.findProvince(province);
        String cityResult = provincesMapper.findCity(city);
        String areaResult = provincesMapper.findArea(area);

        Map<String, String> map = new HashMap<>();
        map.put("province",provinceResult);
        map.put("city",cityResult);
        map.put("area",areaResult);
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> wxAddressChange(Integer nationalCode){
        YxAreas area = provincesMapper.findAreaById(nationalCode);
        Boolean isCityCodeFlag= false;
        if (null ==area) {
            YxAreasNew yxAreasNew = areasNewMapper.queryAreaByCode(nationalCode.toString());
            if (null !=yxAreasNew) {
                YxAreas yxAreas = new YxAreas();
                yxAreas.setArea(yxAreasNew.getName());
                yxAreas.setCityid(Integer.parseInt(yxAreasNew.getParentCode()));
                yxAreas.setAreaid(nationalCode);
                YxCities city = provincesMapper.findCityById(Integer.parseInt(yxAreasNew.getParentCode()));
                if (null == city) {
                    YxCitiesNew yxCitiesNew = areasNewMapper.queryCityByCode(yxAreasNew.getParentCode());
                    if(null !=yxCitiesNew) {
                        YxCities cities = new YxCities();
                        cities.setCity(yxCitiesNew.getName());
                        cities.setCityid(Integer.parseInt(yxAreasNew.getParentCode()));
                        cities.setProvinceid(Integer.parseInt(yxCitiesNew.getParentCode()));
                        YxProvinces province = provincesMapper.findProvinceById(Integer.parseInt(yxCitiesNew.getParentCode()));
                        if (null == province) {
                            YxProvincesNew yxProvincesNew = areasNewMapper.queryProvinceByCode(yxCitiesNew.getParentCode());
                            if(null !=yxProvincesNew) {
                                YxProvinces provinces = new YxProvinces();
                                provinces.setProvince(yxProvincesNew.getName());
                                provinces.setProvinceid(Integer.parseInt(yxProvincesNew.getCode()));
                                provincesMapper.insert(provinces);
                            }
                        }
                        citiesMapper.insertSelective(cities);
                    }
                }
                areasMapper.insert(yxAreas);

                //清楚地址缓存
                this.delRedisAddress();
            } else {
                YxCitiesNew yxCitiesNew = areasNewMapper.queryCityByCode(nationalCode.toString());
                if (null !=yxCitiesNew) {
                    isCityCodeFlag = true;
                    YxCities city = provincesMapper.findCityById(nationalCode);
                    if(city == null) {
                        YxCities cities = new YxCities();
                        cities.setCity(yxCitiesNew.getName());
                        cities.setCityid(Integer.parseInt(yxCitiesNew.getCode()));
                        cities.setProvinceid(Integer.parseInt(yxCitiesNew.getParentCode()));
                        citiesMapper.insertSelective(cities);
                        List<YxAreasNew> yxAreasNews = areasNewMapper.queryAreaByCityCode(nationalCode.toString());
                        if (!CollectionUtils.isEmpty(yxAreasNews)) {
                            yxAreasNews.stream().forEach(areasNew -> {
                                YxAreas yxAreas = new YxAreas();
                                yxAreas.setArea(areasNew.getName());
                                yxAreas.setCityid(Integer.parseInt(areasNew.getParentCode()));
                                yxAreas.setAreaid(Integer.parseInt(areasNew.getCode()));
                                areasMapper.insert(yxAreas);
                            });
                        }

                        //清楚地址缓存
                        this.delRedisAddress();
                    }


                }
            }

        }
        AddressResponse addressResponse = areasNewMapper.queryAddressByNationalCode(nationalCode);
        Map<String, String> map = new HashMap<>();
        map.put("province",addressResponse == null ? "": addressResponse.getProvince());
        map.put("city",addressResponse == null ? "": addressResponse.getCity());
        map.put("area",addressResponse == null ? "": addressResponse.getArea());
        if (isCityCodeFlag) {
            AddressResponse address = areasNewMapper.queryAddressByNationalCityCode(nationalCode);
            map.put("province",address == null ? "": address.getProvince());
            map.put("city",address == null ? "": address.getCity());
        }
        return map;
    }

    public void delRedisAddress(){
        try {
            redisService.delete("address:h5");
            redisService.delete("address:ios");
            redisService.delete("address:android");
            redisService.delete("address:all");
        } catch (Exception e) {
            log.error("清楚地址缓存失败,{}",e.getMessage());
        }
    }


    public YxProvinces addWxProvince(String provinceStr) {
        if (StringUtils.isNotBlank(provinceStr)) {
            JSONObject jsonObject = JSONObject.parseObject(provinceStr);
            YxProvinces provinces = JSONObject.toJavaObject(jsonObject, YxProvinces.class);
            int insertResult = provincesMapper.insert(provinces);
            if (insertResult>0) {
                return provinces;
            }
        }
        return null;
    }


    public YxCities addWxCity(String cityStr) {
        if (StringUtils.isNotBlank(cityStr)) {
            JSONObject jsonObject = JSONObject.parseObject(cityStr);
            YxCities cities = JSONObject.toJavaObject(jsonObject, YxCities.class);
            int insertResult = citiesMapper.insert(cities);
            if (insertResult>0) {
                return cities;
            }
        }
        return null;
    }

    public YxAreas addWxArea(String areaStr) {
        if (StringUtils.isNotBlank(areaStr)) {
            JSONObject jsonObject = JSONObject.parseObject(areaStr);
            YxAreas areas = JSONObject.toJavaObject(jsonObject, YxAreas.class);
            int insertResult = areasMapper.insert(areas);
            if (insertResult>0) {
                return areas;
            }
        }
        return null;
    }
}
